package fileutils

import (
	"gitee.com/ichub/goconfig/common/base/baseconsts"
	"gitee.com/ichub/goconfig/common/base/basedto"
	"github.com/duke-git/lancet/fileutil"
	"github.com/duke-git/lancet/system"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"strings"
)

type GofileUtil struct {
	basedto.BaseEntitySingle
}

func NewGofileUtil() *GofileUtil {
	return &GofileUtil{}
}

const FILE_GOMOD = "go.mod"

func (this *GofileUtil) FindRootPkg() string {
	return os.Getenv(baseconsts.IchubBasePathPkg)
}
func (this *GofileUtil) FindPkgPath(pkg string) string {
	var p, err = ImportPkg(pkg)
	if err != nil {
		logrus.Error(err)
		return ""
	}
	return p.Dir
}

func (this *GofileUtil) SetRootPkgEnv(p string) {
	os.Setenv(baseconsts.IchubBasePathPkg, p)
}

func (this *GofileUtil) CheckConfigFileExist(root, f string) bool {
	return this.TryFileExist(root + f)
}

func (this *GofileUtil) FindRootDir() string {
	var root = this.findRoot(this.GetCurPath(), baseconsts.DEFINE_ENV_PATHFILE)
	var cfgfile = root + "/" + baseconsts.DEFINE_ENV_PATHFILE
	if !this.CheckFileExist(cfgfile) {
		root = this.FindRootDirGoMod()
	}
	return root
}

func (this *GofileUtil) FindRootDirGoMod() string {
	return this.findRoot(this.GetCurPath(), FILE_GOMOD)

}

// go.mod
func (this *GofileUtil) findRoot(curpath, filename string) string {

	var rootdir = os.Getenv(baseconsts.IchubBasePath)
	if len(rootdir) > 0 {
		return rootdir
	}
	rootdir = this.findWorkRoot(curpath, filename)
	os.Setenv(baseconsts.IchubBasePath, rootdir)
	return rootdir
}

func (this *GofileUtil) findWorkRoot(curPath, f string) string {
	var split = "\\"
	if system.IsLinux() {
		split = "/"
	}
	var dirs = strings.Split(curPath, split)
	var workRoot = strings.Join(dirs, split)
	var i = len(dirs)
	for i > 0 {
		if this.CheckConfigFileExist(workRoot, f) {
			os.Setenv(baseconsts.IchubBasePath, workRoot)
			return workRoot
		}
		i--
		workRoot = strings.Join(dirs[0:i], split)
	}
	return workRoot
}

func (this *GofileUtil) GetCurPath() string {

	c, _ := os.Getwd()
	return c
}

func (this *GofileUtil) CheckFileExist(filename string) bool {

	if fileutil.IsExist(filename) {

		return true
	}

	logrus.Warnf("file not exists !%s\r\n", filename)
	return false

}
func (this *GofileUtil) TryFileExist(filename string) bool {

	return fileutil.IsExist(filename)

}
func (this *GofileUtil) UnZip(zipFile string, destPath string) error {
	return fileutil.UnZip(zipFile, destPath)
}

func (this *GofileUtil) Zip(srcPath string, destFile string) error {
	return fileutil.Zip(srcPath, destFile)
}
func (this *GofileUtil) Dir(pathfile string) string {
	return filepath.Dir(pathfile)
}
